package com.r2r.fetus;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.ssssssss.magicapi.Const;
import org.ssssssss.magicapi.mqtt.MqttConnectStatusListener;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.core.TioConfig;
import org.tio.core.exception.TioDecodeException;
import org.tio.core.intf.Packet;
import org.tio.server.intf.TioServerHandler;



/**
 * @author zcg
 */
//@Component
public class FetusServerHandler implements TioServerHandler {
	private static final Logger logger = LoggerFactory.getLogger(FetusServerHandler.class);
   /**
     * 解码：把接收到的ByteBuffer，解码成应用可以识别的业务消息包
     * 总的消息结构：消息头 + 消息体
     * 消息头结构：    4个字节，存储消息体的长度
     * 消息体结构：   对象的json串的byte[]
     */
    @Override
    public FetusPacket decode(ByteBuffer buffer, int limit, int position, int readableLength, ChannelContext channelContext) throws TioDecodeException {
        //Map<String,Object> params = new HashMap<>();
        //params.put("buffer",buffer);
        //return Const.getService().execute("POST","/network/socketServerDecode", params);
        //提醒：buffer的开始位置并不一定是0，应用需要从buffer.position()开始读取数据
        //收到的数据组不了业务包，则返回null以告诉框架数据不够
		buffer.order(Const.byteOrder);
		if (readableLength < FetusPacket.V1HEADER_LENGHT) {
			return null;
		}
		String pcgVersion = (String) channelContext.getAttribute("pcgVersion");
		FetusPacket imPacket = null;
		if(pcgVersion==null || "".equals(pcgVersion.trim())){
			if(readableLength<500)
				return null;
			pcgVersion = "V1";//parsePcgVersion(buffer, readableLength);
			channelContext.setAttribute("pcgVersion", pcgVersion);
		}
		
		if("V1".equals(pcgVersion))
			imPacket=FetusPacketV1.parseFetusPacket(buffer, readableLength);
		if(imPacket!=null) {
			imPacket.setPcgVersion(pcgVersion);
		}
		return imPacket;
    }
    /**
     * 编码：把业务消息包编码为可以发送的ByteBuffer
     * 总的消息结构：消息头 + 消息体
     * 消息头结构：    4个字节，存储消息体的长度
     * 消息体结构：   对象的json串的byte[]
     */
    @Override
    public ByteBuffer encode(Packet packet, TioConfig tioConfig, ChannelContext channelContext) {
		FetusPacket fetusPacket = (FetusPacket) packet;
		byte[] body = fetusPacket.getBody();
		short bodyLen = 0;
		if (body != null) {
			bodyLen = (short) body.length;
		}

		//总长度是消息头的长度+消息体的长度
		short allLen = (short) (FetusPacket.V1HEADER_LENGHT + bodyLen);

		ByteBuffer buffer = ByteBuffer.allocate(allLen);
		buffer.order(tioConfig.getByteOrder());

		//写入包头
		buffer.put(FetusPacket.v1Header1);	
		if(fetusPacket.getType()==Type.PKG_PATIENT){
			//写入消息体长度
			buffer.putShort((short)(bodyLen+2));
			//写入床位号
			buffer.put(fetusPacket.getBedNo());	
		}else
		{
			//写入消息体长度
			buffer.putShort((short)(bodyLen+2));
			//写入床位号
			buffer.put(fetusPacket.getBedNo());	
		}
		//写入消息类型
		buffer.put(fetusPacket.getType());

		//写入消息体
		if (body != null) {
			buffer.put(body);
		}
		return buffer;

    }
    /**
     * 处理消息
     */
    @Override
    public void handler(Packet packet, ChannelContext channelContext) throws Exception {
        Map<String,Object> params = new HashMap<>();
        params.put("packet",(FetusPacket) packet);
        Const.getService().execute("POST","/network/socketServerHandler", params);
    }




}